import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../page/bloc/WebRtcCubit.dart';
import '../../util/ImSingleton.dart';

import '../../util/LoggerUtil.dart';
import '../../util/UiUtil.dart';
import '../dto/base/Resp.dart';
import '../dto/business/WebRtcData.dart';
import 'InitRouter.dart';

class WebRtcConsumerRouter {

  final _logger = createLogger();

  void initCallback(Map<String, CallbackData> callbackMap) {
    callbackMap.putIfAbsent(
        "serverRedirectWebRtcInvitation", () => CallbackData(decodeFunction: WebRtcInvitationReq.fromJson, doFunction: receiveInvitation));
    callbackMap.putIfAbsent(
        "serverRedirectWebRtcInvitationResult", () => CallbackData(decodeFunction: WebRtcInvitationResultReq.fromJson, doFunction: receiveInvitationResult));
    callbackMap.putIfAbsent(
        "serverRedirectWebRtcCancel", () => CallbackData(decodeFunction: WebRtcCancelReq.fromJson, doFunction: receiveCancel));
  }

  // 接受服务端转发的聊天邀请
  Future<OkResp> receiveInvitation(WebRtcInvitationReq invitationReq) async {
    _logger.i('webrtc receive invitation, data: ${jsonEncode(invitationReq)}');
    UiUtil.showInvitation(invitationReq);
    return OkResp(coder: 0, successDataTime: DateTime.now());
  }

  // 接受服务端邀请相应结果
  Future<OkResp> receiveInvitationResult(WebRtcInvitationResultReq invitationResultReq) async {
    _logger.i('webrtc receive invitationResult, data: ${jsonEncode(invitationResultReq)}');
    if (!invitationResultReq.isAccept) {
      var context = ImSingleton.getInstance().mainContext!;
    }
    return OkResp(coder: 0, successDataTime: DateTime.now());
  }

  // 接受服务器取消请求
  Future<OkResp> receiveCancel(WebRtcCancelReq cancelReq) async {
    _logger.i('webrtc receive cancel req, data: ${jsonEncode(cancelReq)}');
    var context = ImSingleton.getInstance().mainContext!;
    var webRtcCubit = context.read<WebRtcCubit>();
    webRtcCubit.add(WebRtcCancelEvent());
    return OkResp(coder: 0, successDataTime: DateTime.now());
  }
}